using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Ink;
using System.Xml.Serialization;
using System.IO;

namespace WozLib.UI.Ink.SketchProperties
{

  public class StrokeSketchProperty : SketchProperty
  {
    // in case the get is used a lot we optimize by converting to a stroke the first time and using that as the source

    [XmlAttribute("Data")]
    public byte[] _Data;
    private Stroke _DataCache = null;

    [XmlIgnore]
    public Stroke Data
    {
      get 
      {
        if (_DataCache == null)
        {
          MemoryStream memoryStream = new MemoryStream(_Data);
          StrokeCollection strokes = new StrokeCollection(memoryStream);
          if (strokes.Count > 0)
          {
            _DataCache = strokes[0];
          }
        }

        return _DataCache;
      }

      set 
      {
        // invalidate the cache
        _DataCache = null;

        StrokeCollection strokes = new StrokeCollection();
        strokes.Add(value);
        MemoryStream memoryStream = new MemoryStream();
        strokes.Save(memoryStream);
        _Data = memoryStream.ToArray();

        // we don't update the cache until a "get" because if it is 
        // never used again it would be a waste of time and space

        FirePropertyChanged("Data");
        NotifyPropertyChanged();
      }
    }

    // we automatically assign WozPropertyType.Ink to base because Ink is the only type using this property
    public StrokeSketchProperty(Stroke data)
      : base(WozPropertyType.Ink)
    {
      Data = data;
    }

    public StrokeSketchProperty(byte[] data)
      : base(WozPropertyType.Ink)
    {
      _Data = data;
    }

    public StrokeSketchProperty() : base(WozPropertyType.Ink)
    {
    }

    public override object Clone()
    {
      return new StrokeSketchProperty(_Data.Clone() as byte[]);
    }
  }
}
